import App from "../../framework/scripts/App"
import MaskProgressComp from "../../framework/scripts/component/MaskProgressComp"
import EventMgr from "../../framework/scripts/manager/EventMgr"
import GameConstants from "../GameConstants"
import Core from "../core/Core"
import ResCacheMgr from "../manager/ResCacheMgr"
import SceneMgr from "../manager/SceneMgr"

const { ccclass } = cc._decorator


@ccclass
export default class Loading extends cc.Component {
    private maskProgress: MaskProgressComp

    private progressTargets: number[] = [0.2, 0.5, 0.8, 1] //核心资源加载、场景预加载、资源缓存
    private progressStep: number = 0

    private sceneEntered: boolean = false


    protected onLoad(): void {
        App.init()

        Core.init()

        SceneMgr.inst.preloadScenes(GameConstants.preloadScenes)
        ResCacheMgr.inst

        this.maskProgress = this.node.getChildByName('progress').getComponent(MaskProgressComp)

        EventMgr.on(GameConstants.event.CoreLoadOk, this.progressStepPlus, this)
        EventMgr.on(GameConstants.event.ScenePreloadOk, this.progressStepPlus, this)
        EventMgr.on(GameConstants.event.ResCacheLoadOk, this.progressStepPlus, this)
    }

    protected start(): void {
        this.maskProgress.setProgress(0)

        this.updateProgress()
    }

    protected update(_dt: number): void {
        if (this.sceneEntered) return

        if (this.maskProgress.progress == 1) {
            this.sceneEntered = true

            SceneMgr.inst.loadScene(GameConstants.scene.Login)
        }
    }

    protected onDestroy(): void {
        EventMgr.clear(this)
    }


    private progressStepPlus() {
        this.progressStep++

        if (this.progressStep < this.progressTargets.length) {
            this.updateProgress()
        }
    }

    private updateProgress() {
        this.maskProgress.updateProgress(this.progressTargets[this.progressStep])
    }
}
